package com.itheima.reggie_test.web;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie_test.common.Result;
import com.itheima.reggie_test.entity.User;
import com.itheima.reggie_test.service.IUserService;
import com.itheima.reggie_test.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ auther: 小熊
 * @ date:2022/12/20 14:56
 * @Todo :
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码:{}",code);
//            session.setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return Result.success("验证码发送成功");
        }
        return Result.error("验证码发送失败");
    }

    @PostMapping("/login")
    public Result login(@RequestBody Map map,HttpSession session){
        log.info(map.toString());
        String phone = (String) map.get("phone");
        log.info("手机号码1：{}",phone);
        String code = map.get("code").toString();
        log.info("用户验证码：{}",code);

        //session中的验证码
//        String sessionCode = (String) session.getAttribute(phone);
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);

        if (sessionCode != null && sessionCode.equals(code)){
            LambdaQueryWrapper<User> wq = new LambdaQueryWrapper<>();
            wq.eq(User::getPhone,phone);
            User user = userService.getOne(wq);
            if (user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //删除Redis中的验证码缓存 防止攻击
            redisTemplate.delete(phone);
            return Result.success(user);
        }
        return Result.error("登录失败");
    }

    @PostMapping("/loginout")
    public Result logout(HttpSession session){
        session.setAttribute("user",null);
        return Result.success("退出成功");
    }
}
